﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using MDF.Utilites.Helper;
using System.Web.Routing;
using Portalseo.DAO;
using PortalNews.BUS;
using PortalNews.BlogspotNews;
using PortalNews.WordpressNews;
using TGVR_Project.Models;
using WebMatrix.WebData;
using PortalAccount;
using MDF.Utilites.Tools;
using DataHelper;
namespace HomePage.Controllers
{
    public class BaseController : Controller
    {
        //
        // GET: /Base/
        //Đối tượng phân trang
        //Đối tượng xuất kết quả, báo lỗi ra màn hình
        protected MyResult m_Result = new MyResult();
        //Đối tượng phân trang
        protected Pagging m_Pagging = new Pagging();
        protected Lang m_lang = new Lang(1);

        protected SEO m_seo = new SEO();

        public PortalUser LoginUser
        {
            get { return GetCurrentUser(); }
            set { System.Web.HttpContext.Current.Session["CurrentUser"] = value; }
        }

        //protected bool m_IsOpening = !CauHinhDAO.IsOpenWebsite();

        public BaseController()
        {
            //WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            //IBoot boot = new AbayBoot();
            // boot.Get(0, 0, DateTime.Now, DateTime.Now, 0, 0, 0);

            //IBoot boot = new AbayBoot();

            //boot.Get("SGN", "DAD", DateTime.Now, DateTime.Now.AddDays(10), 1, 0, 0);

            if (System.Web.HttpContext.Current.Session["lang"] == null)
                System.Web.HttpContext.Current.Session["lang"] = "1";
            int iLang = Int32.Parse(System.Web.HttpContext.Current.Session["lang"].ToString());
            m_lang = new Lang(iLang);

            if (System.Web.HttpContext.Current.Request.QueryString["lang"] != null)
            {
                string strLang = System.Web.HttpContext.Current.Request.QueryString["lang"].ToString();
                int iLangTemp = 1;
                if (Int32.TryParse(strLang, out iLangTemp))
                {
                    m_lang = new Lang(iLangTemp);
                }
            }

            m_seo = new SeoBUS().Get(m_lang.iLang);
            if (m_seo == null)
                m_seo = new SEO();
            ViewBag.SEO = m_seo;
            ViewBag.Lang = m_lang;
            ViewBag.Pagging = this.m_Pagging;
            ViewBag.Result = this.m_Result;
            bool IsLogin = IsLogined();
            ViewBag.IsLogOn = IsLogin;
            ViewBag.LoginUser = GetCurrentUser();

            // Tin tức
            NewsBUS nBUS = new NewsBUS();

            ViewBag.QuestionNews = nBUS.GetAll(3, m_lang.iLang);
            ViewBag.AboutUs = nBUS.GetAll(4, m_lang.iLang);
            ViewBag.PurchaseNews = nBUS.GetAll(5, m_lang.iLang);
            ViewBag.InterTicketNews = nBUS.GetAll(6, m_lang.iLang);
            ViewBag.DomesticTicketNews = nBUS.GetAll(7, m_lang.iLang);
            ViewBag.FirmTicketNews = nBUS.GetAll(8, m_lang.iLang);
            ViewBag.TypeTicketNews = nBUS.GetAll(9, m_lang.iLang);


            FlightSearchModelView viewModel = new FlightSearchModelView();
            viewModel.DatePickerDepartDate.SelectedDate = viewModel.DatePickerDepartDate.SelectedDate ?? DateTime.Today;
            viewModel.DatePickerDepartDate.MinDate = viewModel.DatePickerDepartDate.MinDate ?? new DateTime(1900, 1, 1);
            viewModel.DatePickerDepartDate.MaxDate = viewModel.DatePickerDepartDate.MaxDate ?? new DateTime(2099,
                12, 31);
            viewModel.DatePickerDepartDate.ShowButton = viewModel.DatePickerDepartDate.ShowButton ?? true;
            viewModel.DatePickerDepartDate.OpenOnFocus = viewModel.DatePickerDepartDate.OpenOnFocus ?? false;
            //Return date
            viewModel.DatePickerReturnDate.SelectedDate = viewModel.DatePickerReturnDate.SelectedDate;
            viewModel.DatePickerReturnDate.MinDate = DateTime.Today;
            viewModel.DatePickerReturnDate.MaxDate = viewModel.DatePickerReturnDate.MaxDate ?? new DateTime(2099,
                12, 31);
            viewModel.DatePickerReturnDate.ShowButton = viewModel.DatePickerReturnDate.ShowButton ?? true;
            viewModel.DatePickerReturnDate.OpenOnFocus = true;
            //Depart time
            viewModel.TimePickerDepartDate.SelectedDate = viewModel.TimePickerDepartDate.SelectedDate ?? new
                DateTime(2010, 1, 1, 10, 0, 0);
            viewModel.TimePickerDepartDate.MinTime = viewModel.TimePickerDepartDate.MinTime ?? DateTime.Today;
            viewModel.TimePickerDepartDate.MaxTime = viewModel.TimePickerDepartDate.MaxTime ?? new DateTime(2010,
                1, 1, 18, 0, 0);
            viewModel.TimePickerDepartDate.ShowButton = viewModel.TimePickerDepartDate.ShowButton ?? true;
            viewModel.TimePickerDepartDate.Interval = viewModel.TimePickerDepartDate.Interval ?? 30;
            viewModel.TimePickerDepartDate.OpenOnFocus = true;
            //Return time
            viewModel.TimePickerReturnDate.SelectedDate = viewModel.TimePickerReturnDate.SelectedDate ?? new
                DateTime(2010, 1, 1, 10, 0, 0);
            viewModel.TimePickerReturnDate.MinTime = viewModel.TimePickerReturnDate.MinTime ?? new DateTime(2010,
                1, 1, 8, 0, 0);
            viewModel.TimePickerReturnDate.MaxTime = viewModel.TimePickerReturnDate.MaxTime ?? new DateTime(2010,
                1, 1, 18, 0, 0);
            viewModel.TimePickerReturnDate.ShowButton = viewModel.TimePickerReturnDate.ShowButton ?? true;
            viewModel.TimePickerReturnDate.Interval = viewModel.TimePickerReturnDate.Interval ?? 30;
            viewModel.TimePickerReturnDate.OpenOnFocus = viewModel.TimePickerReturnDate.OpenOnFocus ?? false;
            ViewBag.ways = 1;

            PortalTicket.BUS.StationBUS sBus = new PortalTicket.BUS.StationBUS();


            ViewData["LSTCITYFROM"] = sBus.GetAllName();
            ViewData["LSTCITYTO"] = ViewData["LSTCITYFROM"];

            //window
            ViewData["modal"] = false;
            ViewData["scrolling"] = true;
            ViewData["resizable"] = true;
            ViewData["movable"] = true;

            ViewData["viewModel"] = viewModel;
        }

        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            HttpCookie cc = new HttpCookie("sessionid");
            cc = Request.Cookies["sessionid"];

            if (System.Web.HttpContext.Current.Request.QueryString["lang"] != null)
            {
                string strLang = System.Web.HttpContext.Current.Request.QueryString["lang"].ToString();
                int iLangTemp = 1;
                if (Int32.TryParse(strLang, out iLangTemp))
                    System.Web.HttpContext.Current.Session["lang"] = System.Web.HttpContext.Current.Request.QueryString["lang"];
                System.Web.HttpContext.Current.Session["lang"] = iLangTemp.ToString();
            }

            string FromHomeURL = "http://www.thegioivere.net/";
            string ToHomeURL = "http://thegioivere.net/";

            if (System.Web.HttpContext.Current.Request.Url.ToString().ToLower().Contains(FromHomeURL))
            {
                System.Web.HttpContext.Current.Response.Status = "301 Moved Permanently";
                System.Web.HttpContext.Current.Response.AddHeader("Location",
                Request.Url.ToString().ToLower().Replace(FromHomeURL, ToHomeURL));
            }
        }

        private PortalUser GetCurrentUser()
        {
            var objUser = System.Web.HttpContext.Current.Session["CurrentUser"];
            if (objUser != null)
                return (PortalUser)objUser;
            LoginUser = new PortalUser();
            return null;
        }

        protected bool IsLogined()
        {
            return false;
        }

        protected virtual bool IsAccess()
        {
            return false;
        }

        protected string SaveFile(HttpPostedFileBase file, int _iWidth = 1000, int _iHeight = 300)
        {
            if (file != null)
            {
                var fileNameImage = Path.GetFileName(file.FileName).ToLower();
                string[] strArr = fileNameImage.Split('.');
                if (strArr.Length < 2)
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage("Không nhận biết được tâp tin của bạn");
                    return "";
                }
                string strExtend = "." + strArr[strArr.Length - 1];

                if (strExtend.ToLower().IndexOf("jpg")==-1 
                    &&strExtend.ToLower().IndexOf("png")==-1 
                    &&strExtend.ToLower().IndexOf("jpge")==-1)
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage("Không nhận biết được tâp tin của bạn");
                    return "";
                }
                fileNameImage = DateTime.Now.ToString("yyMMddhhmmss") + fileNameImage;

                string strPath = Server.MapPath("~/Content/Files");
                if (!Directory.Exists(strPath))
                {
                    Directory.CreateDirectory(strPath);//không tồn tại thu mục
                }
                if (!Directory.Exists(strPath))//không tạo dc thư mục
                {
                    this.m_Result.IsSuccess = -1;
                    this.m_Result.AddMessage("Không thể tạo thư mục");
                    this.m_Result.AddMessage("Lỗi hệ thống. Vui lòng liên hệ ban quản trị");
                    return "";
                }

                var strPathFull = strPath;
                if (!Directory.Exists(strPathFull))
                {
                    Directory.CreateDirectory(strPathFull);//không tồn tại thu mục
                }
                var path = Path.Combine(strPathFull, fileNameImage);
                file.SaveAs(path);
                //path = Path.Combine(strPathThumb, fileName);
                //file.SaveAs(path);

                ImageHelper.ResizeImage(strPathFull + "\\" + fileNameImage, strPathFull + "\\" + fileNameImage, _iWidth, _iHeight, true);
                return "/Content/Files/" + fileNameImage;
            }
            return "";
        }

        public ActionResult RedirectToHome()
        {
            NewsBUS nBUS = new NewsBUS();
            ViewBag.LatestNews = nBUS.GetlatestNews(m_lang.iLang, 4);
            ViewBag.LatestPinNews = nBUS.GetlatestPinedNews(m_lang.iLang, 2);
            ViewBag.Title = m_seo.Title;
            return View("HomeIndexRedirect", new FlightSearchModelView());
        }

    }
}
